import cache from "@/utils/cache.js";
import {
	cacheConstants,
	constants
} from "@/config/constants.js";
import user from "@/utils/user.js";


// 需要修改token，和根据实际修改请求头
export default (params) => {
	// 全局请求封装
	const base_url = import.meta.env.VITE_BASE_IP;
	const protocol = import.meta.env.VITE_BASE_PROTOCOL;

	// 请求超出时间
	const timeout = 20000
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	const token = cache.getCache(cacheConstants.user_token);
	const authorization = constants.authorization;
	let header = {
		authorization: 'Bearer ' + token,
		...params.header
	}
	// if (method == "post") {
	// header = {
	// 	'Content-Type': 'application/json'
	// };
	// }
	return new Promise((resolve, reject) => {
		uni.request({
			url: protocol + "://" + base_url + url,
			method: method,
			header: header,
			data: data,
			timeout,
			success(response) {
				// 根据返回的状态码做出对应的操作
				//获取成功
				// console.log(res.statusCode);
				if (response.data.code == 200) {
					// console.log(response.data)
					resolve(response.data);
				} else {
					// uni.clearStorageSync()
					switch (response.data.code) {
						case 401:
							uni.redirectTo({
								url: "/pages/login/login"
							});
							break;
						case 404:
							uni.showToast({
								title: '请求地址不存在...',
								duration: 2000,
							})
							break;
						case 500:
							uni.showToast({
								icon: 'none',
								title: response.data.msg,
								duration: 2000
							});
							break;
						default:
							uni.showToast({
								title: '请重试...',
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				console.log(err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);

			},
			complete() {
				// 不管成功还是失败都会执行
				// uni.hideLoading();
				// uni.hideToast();
			}
		});
	}).catch(() => {});
};